﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Security.Principal;

namespace WorkStation.Frameworks.Core.Json
{
    /// <summary>
    /// * Json数据辅助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// * 引用类型转换成JSON
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToJson(object value)
        {
            #region * 另一种方法
            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(value.GetType());
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    serializer.WriteObject(ms, value);
            //    StringBuilder sb = new StringBuilder();
            //    sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
            //    return sb.ToString();
            //}  
            #endregion

            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

            return js.Serialize(value);
        }

        /// <summary>
        /// * JSON转换成对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T ToObject<T>(string jsonString)
        {
            #region * 另一种方法
            //DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            //MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            //T jsonObject = (T)ser.ReadObject(ms);
            //ms.Close();
            //return jsonObject;
            #endregion
            
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

            return js.Deserialize<T>(jsonString);
        }  
    }
}
